package minisoft.application.loterryservice;

import static minisoft.application.loterryservice.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static minisoft.application.loterryservice.CommonUtilities.SENDER_ID;
import static minisoft.application.loterryservice.CommonUtilities.SERVER_URL;
import static minisoft.application.loterryservice.CommonUtilities.EXTRA_MESSAGE;

import com.google.android.gcm.GCMRegistrar;
import minisoft.application.loterryservice.ServerUtilities;

import minisoft.application.loterryservice.R;

import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends Activity {
	TextView mDisplay;
	AsyncTask<Void, Void, Void> mRegisterTask;
	private static final int RESULT_SETTINGS = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mDisplay = (TextView) findViewById(R.id.textUserSettings);
		//UserDataSource userDS = new UserDataSource(getApplicationContext());
		//Context context = getApplicationContext();
		SharedPreferences sharedPrefs = this.getSharedPreferences(
				this.getPackageName() + "_preferences", Context.MODE_PRIVATE);
		
		String region = sharedPrefs.getString("region", "hu hu hu"); 
		
		//String abc = userDS.getRegion();
		mDisplay.setText(region);//
		
		// Registration
		//boolean flag = false;
		checkNotNull(SERVER_URL, "SERVER_URL");
		checkNotNull(SENDER_ID, "SENDER_ID");
		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(this);
		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(this);

		
		registerReceiver(mHandleMessageReceiver, new IntentFilter(
				DISPLAY_MESSAGE_ACTION));
		final String regId = GCMRegistrar.getRegistrationId(this);
		if (regId.equals("")) {
			// Automatically registers application on startup.
			GCMRegistrar.register(this, SENDER_ID);
		} else {
			// Device is already registered on GCM, check server.
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.
				//mDisplay.append(getString(R.string.already_registered) + "\n");
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						boolean registered = ServerUtilities.register(context,
								regId);
						// At this point all attempts to register with the app
						// server failed, so we need to unregister the device
						// from GCM - the app will try to register again when
						// it is restarted. Note that GCM will send an
						// unregistered callback upon completion, but
						// GCMIntentService.onUnregistered() will ignore it.
						if (!registered) {
							GCMRegistrar.unregister(context);
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}
		// End of registration

		ImageButton ibtnSearch = (ImageButton) this
				.findViewById(R.id.ibtnSearch);

		ibtnSearch.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// Intent intent = new Intent(MainActivity.this, Setting.class);
				// startActivity(intent);

				Intent i = new Intent(MainActivity.this,
						SearchActivity.class);
				startActivityForResult(i, RESULT_SETTINGS);

			}
		});		

		ImageButton ibtnSetting = (ImageButton) this
				.findViewById(R.id.ibtnsetting);

		ibtnSetting.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// Intent intent = new Intent(MainActivity.this, Setting.class);
				// startActivity(intent);

				Intent i = new Intent(MainActivity.this,
						UserSettingActivity.class);
				startActivityForResult(i, RESULT_SETTINGS);

			}
		});

		ImageButton ibtnToday = (ImageButton) this.findViewById(R.id.ibtnToday);

		ibtnToday.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(MainActivity.this,
						TodayActivity.class);
				startActivity(intent);
			}
		});

		// showUserSettings();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.settings, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.menu_settings:
			Intent i = new Intent(this, UserSettingActivity.class);
			startActivityForResult(i, RESULT_SETTINGS);
			break;

		}

		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case RESULT_SETTINGS:
			showUserSettings();
			break;
		}
	}

	private void showUserSettings() {
		SharedPreferences sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);

		StringBuilder builder = new StringBuilder();

		builder.append("\n Username: "
				+ sharedPrefs.getString("prefUsername", "NULL"));

		builder.append("\n Send report:"
				+ sharedPrefs.getBoolean("prefSendReport", false));

		builder.append("\n Sync Frequency: "
				+ sharedPrefs.getString("prefSyncFrequency", "NULL"));

		TextView settingsTextView = (TextView)findViewById(R.id.textUserSettings);

		settingsTextView.setText(builder.toString());

	}

	@Override
	protected void onDestroy() {
		if (mRegisterTask != null) {
			mRegisterTask.cancel(true);
		}
		unregisterReceiver(mHandleMessageReceiver);
		GCMRegistrar.onDestroy(this);
		super.onDestroy();
	}

	private void checkNotNull(Object reference, String name) {
		if (reference == null) {
			throw new NullPointerException(getString(R.string.error_config,
					name));
		}
	}

	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			/*
			 * String newMessage = ""; Bundle bundle=intent.getExtras(); if
			 * (bundle != null) { Set<String> keys = bundle.keySet();
			 * Iterator<String> it = keys.iterator();
			 * 
			 * while (it.hasNext()) { String key = it.next();
			 * 
			 * newMessage = newMessage + ";" + key + "=" + bundle.get(key); } }
			 * //String newMessage = intent.getStringExtra("message") + "\n" +
			 * intent.getStringExtra("tickerText");
			 */
			String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
			// mDisplay.append(newMessage + "\n");
		}
	};

}
